# -*- conding:UTF-8 -*-

'''
@ Project: P8_02_LumenIM-flask
@ File: contact_app.py
@ Author: 罗婷
@ Date：2022/7/10 20:11

'''
import json

import redis
from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, reqparse, marshal

from common.celery.tasks import send_sms
from common.model_fields.user_fs import user_fieklds
from common.models import db
from common.models.users import Users, Friends
from common.utils.login_auth import login_requir

contact_bp = Blueprint('contact_bp', __name__, url_prefix='/api/v1/contact')
api = Api(contact_bp)

# 搜索好友
class FandFriend(Resource):
    @login_requir
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        args = parser.parse_args()
        mobile = args['mobile']
        print('接收到的好友手机号', mobile)
        if mobile:
            uid = g.uid
            friend = Users.query.filter_by(mobile=mobile).first()
            if friend:  # 能查到好友
                friend_data = marshal(friend, user_fieklds)
                return jsonify(message='查询成功', code=200, data=friend_data)
            else:
                return jsonify(message='该用户不存在', code=400)

# 查询好友信息
class FriendDetail(Resource):
    @login_requir
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('user_id')
        args = parser.parse_args()
        friend_id = args['user_id']
        print('查询好友信息!!!!~~~~~~接收到的好友id', friend_id)
        if friend_id:
            uid = g.uid
            friend = Users.query.filter_by(id=friend_id).first()
            # friend = Friends.query.filter_by(friend_id=friend_id, user_id=uid).first()
            if friend:  # 能查到好友
                friend_data = marshal(friend, user_fieklds)
                return jsonify(message='查询成功', code=200, data=friend_data)
            else:
                return jsonify(message='该用户不存在', code=400)

# 添加好友
class AddFriend(Resource):
    @login_requir
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('friend_id')
        parser.add_argument('remark')
        args = parser.parse_args()
        remark = args['remark']
        friend_id = args['friend_id']
        print('接收到的好友id', friend_id, '备注', remark)
        uid = g.uid
        num = Friends.query.filter_by(user_id=friend_id, friend_id=g.uid).count()

        if num > 0:
            return jsonify(message='该用户已经是好友了', code=400)

        if friend_id and remark:
            try:
                # 好友视角下 我是好友 好友是本人    查看好友申请列表  好友查看
                fre = Friends(user_id=friend_id, friend_id=uid, is_follow=False, remark=remark)
                db.session.add(fre)
                db.session.commit()
            except Exception as e:
                print(f'添加好友申请失败{e}')
                return jsonify(message='申请失败', code=400)
            return jsonify(message='添加好友申请成功', code=200)

# 查看好友申请列表
class ShowApply(Resource):
    @login_requir
    def get(self):
        if g.uid:
            print('g.uid', g.uid)
            friends = Friends.query.filter_by(user_id=g.uid, is_follow=False).all()
            print('好友申请', friends)
            fr_apply = []
            if friends:  # 有申请
                for i in friends:
                    friend = Users.query.filter_by(id=i.friend_id).first()
                    friend_data = json.loads(json.dumps(marshal(friend, user_fieklds)))
                    friend_data.update({'created_at': i.created_at, 'remark': i.remark})
                    fr_apply.append(friend_data)
                return jsonify(message='查询成功', code=200, data=fr_apply)
            else:
                return jsonify(message='暂未有用户申请', code=200, data='')

# 同意好友申请信息
class AgreeApply(Resource):
    @login_requir
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('apply_id')
        parser.add_argument('remark')
        args = parser.parse_args()
        remark = args['remark']
        apply_id = args['apply_id']
        print('需要同意的好友id', apply_id, '备注', remark)

        rds = redis.Redis(db=10)
        key = f'{g.uid}_fs'
        res = rds.sadd(key, apply_id)
        print('res', res)
        if res:
            try:
                Friends.query.filter_by(user_id=g.uid, friend_id=apply_id).update({'is_follow': True, 'remark': remark})
                db.session.commit()
            except Exception as e:
                print(f'同意好友申请失败{e}')
                return jsonify(message='添加失败', code=400)
        return jsonify(message='添加好友成功', code=200)

# 拒绝好友申请  删除申请表信息
class RejectApply(Resource):
    @login_requir
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('apply_id')
        parser.add_argument('remark')
        args = parser.parse_args()
        remark = args['remark']
        apply_id = args['apply_id']
        print('拒绝的好友id', apply_id, '备注', remark)
        uid = g.uid
        try:
            # 好友视角下 我是好友 好友是本人    查看好友申请列表  好友查看
            Friends.query.filter_by(user_id=uid, friend_id=apply_id).delete()
            db.session.commit()
        except Exception as e:
            print(f'拒绝失败{e}')
            return jsonify(message='拒绝失败', code=400)
        return jsonify(message='拒绝添加好友成功', code=200)

# 好友列表
class FriendsList(Resource):
    @login_requir
    def get(self):
        uid = g.uid
        rds = redis.Redis(db=10)
        key = f'{uid}_fs'
        res = rds.smembers(key)
        if not res:
            return jsonify(message='还未有好友', code=200, data='')
        f_list_id = [i.decode() for i in res]
        friend_list = []
        for i in f_list_id:
            user = Users.query.filter_by(id=i).first()
            user_data = marshal(user, user_fieklds)
            friend_list.append(user_data)
        return jsonify(message='ok', code=200, data=friend_list)

# 删除好友  friend_id
class DelFriends(Resource):
    @login_requir
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('friend_id')
        args = parser.parse_args()
        friend_id = args['friend_id']
        print('接收到的好友id', friend_id)
        if friend_id:
            uid = g.uid
            rds = redis.Redis(db=10)
            key = f'{uid}_fs'
            res = rds.srem(key, friend_id)
            if res:
                return jsonify(message='删除成功', code=200)
            else:
                return jsonify(message='删除失败', code=200)

# 好友列表
api.add_resource(FriendsList, '/list')
# 删除好友
api.add_resource(DelFriends, '/delete')
# 搜索好友
api.add_resource(FandFriend, '/search')
# 添加好友
api.add_resource(AddFriend, '/apply/create')
# 查询好友信息
api.add_resource(FriendDetail, '/detail')
# 查看好友申请列表
api.add_resource(ShowApply, '/apply/records')
# 同意好友申请信息
api.add_resource(AgreeApply, '/apply/accept')
# 拒绝好友申请
api.add_resource(RejectApply, '/apply/decline')


